# Create your views here.

from django.http import HttpResponse
from django.contrib.csrf.middleware import csrf_exempt
from django.contrib.auth.models import User

from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D

from transport.models import GPSLog
from transport.models import ErrorReport
from transport.helpers import contains_keys
from transport.helpers import render_json
from transport.predict import predict, CONVERT

from commons.content.social.models import FacebookProfile
from commons.content.social.views import create_username

import json
import datetime

CONVERT = 1000000.0

def parse_json_from_request(request):
  if request.method == 'POST':
    json_request = ''
    data = request.POST.keys()
    if len(data) == 1:
      return json.loads(data[0])
  return {}

@csrf_exempt
def facebook_login(request):
  if request.method == 'POST':
    data = parse_json_from_request(request)
    if data.has_key('fuser_id'):
      try:
        f_user = FacebookProfile.objects.get(uid=data['fuser_id'])
        return HttpResponse({'success': True, 'user_id': f_user.user.pk})
      except:
        return HttpResponse({'success': False, 'code': 'REQUIRE_INFO'})
  return HttpResponse({'success': False, 'message': 'Insufficient information.'})

@csrf_exempt
def facebook_information(request):
  if request.method == 'POST':
    data = parse_json_from_request(request)
    if data.has_key('fuser_id') and data.has_key('name') and \
       data.has_key('email') and data.has_key('link'):
      try:
        f_user = FacebookProfile.objects.get(uid=data['fuser_id'])
        return HttpResponse(json.dumps({'success': True, 'user_id': f_user.user.id}))
      except FacebookProfile.DoesNotExist:
        name = data['name'].split(' ')
        first_name = ' '.join(name[0:-1])
        print first_name
        last_name = ' '.join(name[-1:])
        user = User(
          username=create_username(data['link'], first_name),
          first_name=first_name,
          last_name=last_name,
          email=data['email']
        )
        user.set_unusable_password()
        user.save()

        f_user = FacebookProfile(
          user=user,
          uid=data['fuser_id'],
          link=data['link']
        )
        f_user.save()
        return HttpResponse(json.dumps({'success': True, 'user_id': user.pk}))
  return HttpResponse(json.dumps({'success': False, 'message': 'Insufficient information.'}))
      
@csrf_exempt
def create_user(request):
  result = {'success': False}

  if request.method == 'POST':
    data = parse_json_from_request(request)

    if data.has_key('username') and data.has_key('pass') and \
       data.has_key('pass_again') and data.has_key('email') and \
       data.has_key('name'):
      if data['pass'] == data['pass_again']:
        user = User.objects.create()
      else:
        result['message'] = 'Password does not match.'

  return HttpResponse(json.dumps(result))

@csrf_exempt
def log_gps(request):
  if request.method == 'POST':
    data = parse_json_from_request(request)
    if contains_keys(data, 'user_id', 'x', 'y', 'timestamp'):
      try:
        user = User.objects.get(pk=data['user_id'])
      except User.DoesNotExist:
        return render_json({'success': False, 'message': 'User does not exist.'})
      timestamp = datetime.datetime.strptime(data['timestamp'], '%Y-%m-%dT%H:%M:%S')
      logs = GPSLog.objects.filter(
        user=user,
        x=int(data['x']),
        y=int(data['y']),
        timestamp=timestamp
      )
      if len(logs) == 0:
        log = GPSLog(
          user=user, 
          x=int(data['x']),
          y=int(data['y']),
          timestamp=timestamp,
          time=timestamp.time(),
          geom=Point(int(data['x'])/CONVERT, int(data['y'])/CONVERT)
        )
        log.save()
      return render_json({'success': True})
    else:
      return render_json({'success': False, 'message': 'Insufficient arguments'})
  return render_json({'success': False, 'message': 'Something went wrong!'})

def view_recording(request):
  logs = GPSLog.objects.all()[1:100]

@csrf_exempt
def report_error(request):
  if request.method == 'POST':
    data = parse_json_from_request(request)
    if contains_keys(data, 'message', 'tag'):
      user_id = data.get('user_id', None)
      if user_id is not None:
        try:
          user = User.objects.get(id=data['user_id'])
        except User.DoesNotExist:
          return render_json({'success': False, 'message': 'User does not exist.'})
        report = ErrorReport(user=user, message=data['message'], tag=data['tag'])
      else:
        report = ErrorReport(message=data['message'], tag=data['tag'])
      report.save()
      return render_json({'success': True})
  return render_json({'success': False})


@csrf_exempt
def get_prediction(request):
  if request.method == 'GET':
    data = request.GET.copy()
    if contains_keys(data, 'user_id', 'x', 'y', 'ptime'):
      data['x'] = int(data['x'])/CONVERT
      data['y'] = int(data['y'])/CONVERT
      data['ptime'] = datetime.datetime.strptime(
        data['ptime'],
        '%Y-%m-%dT%H:%M:%S'
      ).time()

      p_pos = predict(
        user_id=data['user_id'],
        x=data['x'],
        y=data['y'],
        ptime=data['ptime']
      )
      if p_pos is not None:
        return render_json({
          'success': True,
          'x': int(p_pos[0]*CONVERT),
          'y': int(p_pos[1]*CONVERT),
          'found': True
        })
      else:
        return render_json({'success': True, 'found': False})
  return render_json({'success': False})


